package anfangcron

import (
	"time"
	"HTanfang/htmodels"
	"anfang/models"
	"log"
	"fmt"
	"strconv"
	"HTanfang/Util"
)

func StartCheckOffline() {
	time.Sleep(time.Second * 30)
	ticker := time.NewTicker(time.Second * 5)
	for _ = range ticker.C {
		fmt.Println("normal check! every five second")
		CheckOffLineDevice()
	}
}

func CheckOffLineDevice() {
	Devices := []models.Devices{}
	if err := htmodels.GetDevicesOffLine(&Devices, time.Minute * 2); err != nil {
		log.Println("get offline devices error!" + time.Now().String())
		return
	}
	for _, v := range Devices {
		user := models.Users{Id:v.User}
		if err := htmodels.HTUsersGetDetail(&user); err != nil {
			fmt.Println("fatal error when get user " + strconv.Itoa(v.User) + err.Error())
		}
		if anfangutil.CacheNotExist("deviceOffLine" + strconv.Itoa(v.Id), v.Id, v.WXPushInterval) {
			anfangutil.SendAlarmMessage(&user, v.Id, 0, fmt.Sprintf("设备（Id:%d）掉线,最后出现时间为%s", v.Id, v.DeviceUpdateTime.String()), v.DeviceName, v.DevicePosition, v.DeviceType, 0)
		}
	}
}